const express = require('express');
const Admin = require("../db/models/admin");
const bcrypt = require('bcrypt');
const token = require("../middleware/jwt")
module.exports = {

    async login(req, res) {
        const { username, password } = req.body
        // 查询数据库是否存在该用户
        Admin.findOne({
            where: {
                username: username,
            }
        }).then(user => {
            if (user) {
                // 比较密码
                if (bcrypt.compareSync(password, user.password)) {
                    // 生成token
                    const tokenStr = token.getTokenAdmin(user.id, user.username)
                    res.json({
                        code: 200,
                        message: '登录成功',
                        data: user,
                        token: tokenStr
                    })
                } else {
                    res.json({
                        code: 400,
                        message: '密码错误',
                        data: null
                    })
                }
            } else {
                res.json({
                    code: 400,
                    message: '用户不存在',
                    data: null
                })
            }
        })

    },
    async register(req, res) {
        const { name, avatar, desc, username, password } = req.body
        // 查询数据库是否存在该用户
        Admin.findOne({
            where: {
                username: username
            }
        }).then(user => {
            if (user) {
                res.json({
                    code: 400,
                    message: '用户已存在',
                    data: null
                })
            } else {
                // 密码加密
                const salt = bcrypt.genSaltSync(10);
                const hash = bcrypt.hashSync(password, salt);
                Admin.create({
                    name: name,
                    avatar: avatar,
                    desc: desc,
                    username: username,
                    password: hash
                }).then(user => {
                    res.json({
                        code: 200,
                        message: '注册成功',
                        data: user
                    })
                })
            }
        })
    },

    // 测试中间件
    async test(req, res) {
        // admin才能访问
        // checkTokenAdmin(req, res, next)
        let { userId } = req
        console.log(userId)
        res.send({
            data: userId
        })
    }


}